import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import getTitle from '@/utils/getTitle'
import piniaStore from '@/store'
import { getToken } from '@/utils/token'
import setting from '@/setting'

import homeRouter from './modules/home'
import systemRouter from './modules/system'

export const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/home',
    meta: {
      hidden: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '登录',
      hidden: true
    }
  }
]

export const asyncRoutes: RouteRecordRaw[] = [
  ...homeRouter,
  ...systemRouter,
  {
    path: '/:pathMatch(.*)*',
    name: '404',
    component: () => import('@/views/404/index.vue'),
    meta: { hidden: true }
  }
]

const whiteList = ['/login']
let removeRoutes: any = []

export function resetRouter () {
  removeRoutes.forEach((removeRoute: any) => {
    removeRoute()
  })
  removeRoutes = []
}

export function initRouter () {
  return createRouter({
    history: createWebHashHistory(), // 路由模式
    routes: setting.hasAbpBackend ? constantRoutes : [...constantRoutes, ...asyncRoutes] // 路由规则
  })
}
const router = initRouter()

declare let document: any

router.beforeEach(async (to, from, next) => {
  nprogress.start() // 开始加载进度条
  const name: string = to.meta.title as string
  document.title = getTitle(name)
  if (setting.hasAbpBackend) {
    const hasToken = getToken()
    if (!piniaStore.permissionStore.abpConfig || from.name === 'Login') {
      await piniaStore.permissionStore.getApplicationConfiguration()
    }
    if (hasToken) {
      if (to.path === '/login') {
        next({ path: '/' })
      } else {
        const hasGetUserInfo = piniaStore.userStore.userName
        // 是否有该用户
        if (hasGetUserInfo) {
          next()
        } else {
          try {
            await piniaStore.userStore.handleGetInfo()

            if (piniaStore.permissionStore.policies) {
              // 更新用户路由
              const grantedPolicies = piniaStore.permissionStore.policies
              const accessRoutes = await piniaStore.permissionStore.generateRoutes(grantedPolicies)
              accessRoutes.forEach((route: any) => {
                const removeRoute = router.addRoute(route)
                removeRoutes.push(removeRoute)
              })
            }
            next({ ...to, replace: true })
          } catch (error) {
            console.log(error)
            await piniaStore.userStore.resetToken()
            next(`/login?redirect=${to.path}`)
          }
        }
      }
    } else {
      /* has no token */

      if (whiteList.indexOf(to.path) !== -1) {
        // in the free login whitelist, go directly
        next()
      } else {
        // other pages that do not have permission to access are redirected to the login page.
        next(`/login?redirect=${to.path}`)
      }
    }
  } else {
    next()
  }
})

router.afterEach(() => {
  nprogress.done() // 加载进度条
})

export default router
